package com.css.common.core.utils;


import com.css.common.core.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @description: 幂等性工具类
 * @Title: IdempotentUtil
 * @Author xlw
 * @Package com.invoice.tcc.util
 * @Date 2024/11/18 12:51
 */
@Slf4j
public class IdempotentUtil {


    /**
     * 幂等时间,1分钟
     */
    public static final long IDEMPOTENT_TIME = 60;

    /**
     * 幂等性验证
     *
     * @param key            key
     * @param idempotentTime 幂等时间,单位毫秒
     */
    public static synchronized void verify(String key, long idempotentTime) {
        boolean exists = RedisUtils.exists(key);
        if (exists) {
            throw new ServiceException("请勿重复提交请求，一分钟后再试");
        }
        RedisUtils.put(key, Thread.currentThread().getName(), idempotentTime);
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                IdempotentUtil.verify("a123", 60);
            }).start();
        }

    }

}
